<template>
  <q-avatar class="comp-UserAvatar" color="primary" text-color="white" :size="`${size}px`" :rounded="rounded">
    <q-img v-if="user.picture" :src="user.picture" fit="contain" class="user-avatar-img">
      <template v-slot:loading>
        <q-spinner-ios :size="`${0.5 * size}px`" />
      </template>
    </q-img>
    <div v-else class="fallback" :style="nameAbbrStyle">{{ nameAbbr }}</div>
    <div v-if="showGender">
      <q-icon v-if="user.gender === '男'" name="male" color="blue-8" class="gender-icon" :style="genderStyle" />
      <q-icon v-else-if="user.gender === '女'" name="female" color="pink-5" class="gender-icon rotate-45" :style="genderStyle" />
    </div>
    <q-tooltip v-if="tooltipText">
      {{ tooltipText }}
    </q-tooltip>
  </q-avatar>
</template>

<script>
import { computed, defineComponent } from 'vue'

export default defineComponent({
  name: 'UserAvatar',
  props: {
    user: {
      type: Object,
      required: true
    },
    size: {
      type: Number,
      required: false,
      default: 36,
    },
    rounded: {
      type: Boolean,
      required: false,
      default: false,
    },
    showGender: {
      type: Boolean,
      required: false,
      default: false,
    },
    tooltipText: {
      type: String,
      required: false,
    }
  },
  setup(props) {
    const nameAbbr = computed(() => {
      if (!props.user.name || props.user.name.length === 0) {
        return '--'
      }
      if (props.user.name.length <= 2) {
        return props.user.name
      } else if (props.user.name.length <= 4) {
        return props.user.name.substring(props.user.name.length - 2)
      } else {
        return props.user.name[0]
      }
    })
    const nameAbbrStyle = computed(() => {
      return {
        width: `${props.size}px`,
        fontSize: `${Math.floor(props.size / nameAbbr.value.length) - 1}px`,
        transform: `translateX(-50%) translateY(-50%) scale(${0.3 + 0.2 * nameAbbr.value.length})`
      }
    })
    const genderStyle = computed(() => {
      return {
        fontSize: `${Math.floor(props.size * 0.35)}px`,
        borderRadius: `${Math.floor(props.size * 0.35)}px`,
        right: `-${Math.floor(props.size * 0.085)}px`,
        bottom: `-${Math.floor(props.size * 0.085)}px`,
      }
    })
    return {
      nameAbbr,
      nameAbbrStyle,
      genderStyle
    }
  }
})
</script>

<style lang="scss">
.comp-UserAvatar {
  position: relative;

  .user-avatar-img {
    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .gender-icon {
    position: absolute;
    right: -3px;
    bottom: -3px;
    background: rgba(255, 255, 255, .85);
    border-radius: 14px;
  }

  .fallback {
    position: absolute;
    top: 50%;
    left: 50%;
    transform-origin: center center;
    transform: translateX(-50%) translateY(-50%);
    line-height: 1;
    text-align: center;
    text-transform: uppercase;
  }
}
</style>
